package vertx;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.templ.thymeleaf.ThymeleafTemplateEngine;

public class TemplateVerticle  extends AbstractVerticle {

  // 第一步 声明router
  Router router;

  // 第一步 声明 ThymeleafTemplateEngine
  ThymeleafTemplateEngine thymeleafTemplateEngine;

  @Override
  public void start(Future<Void> startFuture) throws Exception {

    // 第二步 初始化Router
    router = Router.router(vertx);

    // 第二步 初始化ThymeleafTemplateEngine
    thymeleafTemplateEngine = ThymeleafTemplateEngine.create(vertx);

    // 第四步 配置Router解析url
    router.route("/").handler(req -> {
      var obj = new JsonObject();
      obj.put("name", "Hello World from backend");
      // 第三步 thymeleafTemplateEngine 直接 render
      thymeleafTemplateEngine.render(obj,
        "templates/index.html",
        bufferAsyncResult -> {
          if(bufferAsyncResult.succeeded()){
            req.response()
              .putHeader("content-type", "text/html")
              .end(bufferAsyncResult.result());
          }else {
            req.response()
              .putHeader("content-type", "text/plain")
              .end(bufferAsyncResult.cause().toString());
          }
      });

    });


    // 第三步 将Router与vertx HttpServer 绑定
    vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
      if (http.succeeded()) {
        startFuture.complete();
        System.out.println("HTTP server started on port 8888");
      } else {
        startFuture.fail(http.cause());
      }
    });
  }
}
